import re
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection
from rest_framework import serializers


# 创建模型类序列化器
from user.models import User


class CreateUserSerializer(serializers.ModelSerializer):
    """创建用户序列化器"""
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile','password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length': '用户名最少5个字符',
                    'max_length': '用户名最多20个字符',
                }
            },
            'password':{
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages':{
                    'min_length': '密码最低8位',
                    'max_length': '密码最高20位',
                }
            }
        }
    def validate(self, attrs):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}', attrs['mobile']):
            raise serializers.ValidationError('手机号码格式错误')
        """检查用户是否同意协议"""
        if attrs['allow'] != 'true':
            raise serializers.ValidationError('请同意用户协议')
        """判断两次密码"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')
        """判断验证码是否正确"""
        # 连接redis数据库
        conn = get_redis_connection('verify')
        rely_sms_code = conn.get('sms_code_%s'%attrs['mobile'])
        if not rely_sms_code:
            raise serializers.ValidationError('验证码已过期')
        rely_sms_code = rely_sms_code.decode()
        if rely_sms_code != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')
        return attrs

    #　创建新的用户
    def create(self, validated_data):

        # 对于数据库来说,有些属性是不需要保存的
        # del validated_data['password2']
        # del validated_data['sms_code']
        # del validated_data['allow']

        # # 调取父类中创建用户的方法
        # user = super().create(validated_data)
        # #　密码进行加密
        # user.set_password(validated_data['password'])
        # user.save()

        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'], mobile=validated_data['mobile'])

        # 使用JWT来生成登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handle = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handle(payload)
        user.token = token
        return user


